<template>
  <div class="container-fluid">
    <div class="todos">
      <h3 class="todo-header">Todo示例</h3>
      <create-form @addItem="handleAddItem"></create-form>
      <div v-for="todo in todoList" :key="todo.id">
        <todo-item
          v-if="!todo.isEditable"
          :todo="todo"
          @deleteTodo="handleDelete"
          @editTodo="handleEdit"
        ></todo-item>
        <edit-todo v-else :todo="todo" @editFinish="handleFinishEdit"></edit-todo>
      </div>
    </div>
  </div>
</template>

<script setup>
import CreateForm from './CreateForm.vue'
import TodoItem from './Todo.vue'
import EditTodo from './EditTodo.vue'
import { ref } from 'vue'

// 初始化todoList为数组
let todoList = ref([])

// 添加新todo
const handleAddItem = (content) => {
  todoList.value.push({
    id: Date.now(), // 使用时间戳作为唯一ID
    content: content,
    isFinished: false,
    isEditable: false,
  })
}

// 删除todo
const handleDelete = (id) => {
  todoList.value = todoList.value.filter((item) => item.id !== id)
}

// 切换编辑状态
const handleEdit = (id) => {
  const todo = todoList.value.find((item) => item.id === id)
  if (todo) {
    todo.isEditable = true
  }
}

// 完成编辑
const handleFinishEdit = (id, content) => {
  const todo = todoList.value.find((item) => item.id === id)
  if (todo) {
    todo.content = content
    todo.isEditable = false
  }
}
</script>

<style lang="scss" scoped>
.container-fluid {
  width: 100%;
  height: 100vh;
  background: #3b36cc;
  display: flex;
  justify-content: center;
  color: white;
}
.todos {
  width: 450px;
  background-color: #1a1a40;
  padding: 20px;
}
.todos > h3 {
  text-align: center;
  margin-top: 20px;
}
</style>
